package com.blackhorse.work;

import com.blackhorse.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer1 {
    public static void main(String[] args) {
        Connection connection = null;
        final Channel channel;
        try {
            connection = ConnectionUtils.getConnection();
            channel = connection.createChannel();
            channel.queueDeclare(Producer.QUEUE_NAME, true, false, false, null);
            //一次只能接受并处理一个消息
            channel.basicQos(1);
            DefaultConsumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("路由key为：" + envelope.getRoutingKey());
                    System.out.println("交换机为：" + envelope.getExchange());
                    System.out.println("消息id：" + envelope.getDeliveryTag());
                    System.out.println("消费者1收到的消息：" + new String(body, "UTF-8"));
                    System.out.println("\n-----------------------------------------------------\n");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //确认消息
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            };
            //监听消息
            channel.basicConsume(Producer.QUEUE_NAME, consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {


        }
    }
}
